package hci.drummer;

import java.io.IOException;
import java.net.Socket;

import hci.drummer.R;
import hci.drummer.connection.Connection;
import hci.drummer.connection.InternetConnection;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class DrummerActivity extends Activity {
	private SensorManager sensorManager;
	private SensorListener sensorListener;
	private CommandPusher commandPusher;
	private Socket socket;

	private UIHandler handler;
	private ProgressDialog connectingDialog;
	private TextView state;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.commandPusher = new CommandPusher();
		this.sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		this.sensorListener = new SensorListener(this.commandPusher);
		this.handler = new UIHandler();
		setContentView(R.layout.main);
		this.state = (TextView)this.findViewById(R.id.state);
	}

	private class TryConnect extends Thread {
		private String ip;
		private int port;

		public TryConnect(String ip, int port) {
			this.ip = ip;
			this.port = port;
		}

		@Override
		public void run() {
			try {
				Connection connection = new InternetConnection(ip, port);
				socket = connection.getSocket();
				commandPusher.startSend(socket);
				Message msg = handler.obtainMessage();
				msg.what = UIHandler.DISPLAY_CONNECT_SUCCEEDED;
				handler.sendMessage(msg);
			} catch (Exception e) {
				Log.d("Drummer", "连接失败");
				Message msg = handler.obtainMessage();
				msg.what = UIHandler.DISPLAY_CONNECT_FAILED;
				handler.sendMessage(msg);
				e.printStackTrace();
			} finally {
				connectingDialog.dismiss();
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, Menu.FIRST + 1, 1, "连接").setIcon(
				android.R.drawable.ic_menu_edit);
		menu.add(Menu.NONE, Menu.FIRST + 2, 2, "断开").setIcon(
				android.R.drawable.ic_menu_close_clear_cancel);
		menu.add(Menu.NONE, Menu.FIRST + 3, 3, "退出").setIcon(
				android.R.drawable.ic_delete);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case Menu.FIRST + 1:
			this.connect();
			break;
		case Menu.FIRST + 2:
			Toast.makeText(this, "断开菜单被点击了", Toast.LENGTH_LONG).show();
			this.disconnect();
			break;
		case Menu.FIRST + 3:
			Toast.makeText(this, "退出菜单被点击了", Toast.LENGTH_LONG).show();
			this.exit();
			break;
		}
		return false;
	}

	private void exit() {
		this.disconnect();
		this.finish();
		System.exit(0);
	}

	private void disconnect() {
		try {
			if (this.socket != null) {
				this.commandPusher.stopWork();
				this.socket.shutdownOutput();
				this.socket.shutdownInput();
				this.socket.close();
				this.socket = null;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void connect() {
		LayoutInflater inflater = (LayoutInflater) getApplicationContext()
				.getSystemService(LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.style, null);
		Builder builder = new Builder(this);
		builder.setView(view);
		builder.setCancelable(true);
		builder.setOnCancelListener(new OnCancelConnectListener());
		builder.setPositiveButton("OK", new OnConnectListener(view));
		builder.setNegativeButton("Cancel", new OnCancelConnectListener());
		builder.show();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER).size() < 1
				|| sensorManager.getSensorList(Sensor.TYPE_ORIENTATION).size() < 1) {
			Toast.makeText(this, "您的设备没有方向||加速度传感器", Toast.LENGTH_LONG);
			return;
		}

		Sensor sensorAccelerometer = sensorManager.getSensorList(
				Sensor.TYPE_ACCELEROMETER).get(0);
		Sensor sensorOrientation = sensorManager.getSensorList(
				Sensor.TYPE_ORIENTATION).get(0);

		sensorManager.registerListener(this.sensorListener, sensorOrientation,
				SensorManager.SENSOR_DELAY_NORMAL);
		sensorManager.registerListener(this.sensorListener,
				sensorAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
	}

	@Override
	protected void onStop() {
		sensorManager.unregisterListener(this.sensorListener);
		super.onStop();
	}

	private class OnConnectListener implements OnClickListener {
		private View view;

		public OnConnectListener(View view) {
			this.view = view;
		}

		@Override
		public void onClick(DialogInterface dialog, int which) {
			connectingDialog = ProgressDialog.show(DrummerActivity.this, "",
					"Connecting…", true);
			dialog.dismiss();
			EditText txtIp = (EditText) view.findViewById(R.id.ip);
			EditText txtPort = (EditText) view.findViewById(R.id.port);
			final TryConnect connector = new TryConnect(txtIp.getText()
					.toString(), Integer.parseInt(txtPort.getText().toString()));

			connectingDialog.setCancelable(true);// 当点击按钮返回的时候Dialog消失
			connectingDialog.setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					connector.stop();
					Log.d("Drummer", "cancelling connecting");
					socket = null;
				}
			});
			connector.start();
		}
	}

	private class OnCancelConnectListener implements OnClickListener,
			OnCancelListener {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			dialog.cancel();
		}

		@Override
		public void onCancel(DialogInterface dialog) {
			dialog.cancel();
		}
	}

	private class UIHandler extends Handler {

		public static final int DISPLAY_CONNECT_SUCCEEDED = 2;
		public final static int DISPLAY_CONNECT_FAILED = 1;

		public UIHandler() {
		}

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UIHandler.DISPLAY_CONNECT_FAILED:
				AlertDialog.Builder dialog = new AlertDialog.Builder(
						DrummerActivity.this);
				state.setText("连接失败");
				dialog.setTitle("Dialog").setMessage("Connect failed")
						.setIcon(android.R.drawable.ic_dialog_info);
				dialog.setPositiveButton("OK",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						});
				dialog.create().show();
				break;
			case UIHandler.DISPLAY_CONNECT_SUCCEEDED:
				state.setText("连接成功");
				Toast.makeText(DrummerActivity.this, "Connected",
						Toast.LENGTH_LONG).show();
			}
		}
	}
}